package com.seuic.hnapps.project;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.logger.Logger;
import com.seuic.hnapps.BaseActivity;
import com.seuic.hnapps.R;
import com.seuic.hnapps.bean.CardBinInfo_bean;
import com.seuic.hnapps.bean.K_binBean;
import com.seuic.hnapps.bean.StatisticalData_bean;
import com.seuic.hnapps.bean.Summary_Bean;
import com.seuic.hnapps.constants.EmvConstants;
import com.seuic.hnapps.posdsdk.pos_func.PosCallbacks;
import com.seuic.hnapps.posdsdk.pos_func.PosFuncs;
import com.seuic.hnapps.util.CWDInterface;
import com.seuic.hnapps.util.CZInterface;
import com.seuic.hnapps.util.CommAdapter;
import com.seuic.hnapps.util.Constants;
import com.seuic.hnapps.util.DateUtil;
import com.seuic.hnapps.util.PinPad;
import com.seuic.hnapps.util.PzGetUtils;
import com.seuic.hnapps.util.ServiceCommon;
import com.seuic.hnapps.util.SpUtils;
import com.seuic.hnapps.util.Up_RundataUtils;
import com.seuic.hnapps.util.Utils;
import com.seuic.hnapps.util.VTAInterface;
import com.solab.enc.DES3;
import com.solab.enc.HexT;
import com.solab.enc.SMS4;
import com.solab.iso8583.IsoMessage;
import com.solab.iso8583.MessageFactory;

import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * isjingkai
 * 2019年7月20日10:39:52
 * 助农取款
 */

public class ToHelpFarmersWithdrawalsActivity extends BaseActivity {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(ToHelpFarmersWithdrawalsActivity.class);
    @BindView(R.id.sure_printingpeper_okbtn)
    Button surePrintingpeperOkbtn;
    @BindView(R.id.sure_printingpeper_layout)
    LinearLayout surePrintingpeperLayout;
    @BindView(R.id.printing_layout)
    LinearLayout printingLayout;
    private PosFuncs posFuncs;


    Runnable runnable;
    Handler handler;
    //卡号
    String bindNum = "";
    //取款金额
    String withdrawalMoney = "";
    //二磁信息
    String track2Data = "";
    //三磁信息
    String track3Data = "";

    String CardType = "";
    //55
    String Field55 = "";

    @BindView(R.id.base_back_btn)
    LinearLayout baseBackBtn;
    @BindView(R.id.base_title_text)
    TextView baseTitleText;
    @BindView(R.id.pleasewyc_image)
    ImageView pleasewycImage;
    @BindView(R.id.pleasewyc_text)
    TextView pleasewycText;
    @BindView(R.id.cancal_btn)
    Button cancalBtn;
    @BindView(R.id.pleasewyc_layout)
    LinearLayout pleasewycLayout;
    @BindView(R.id.verificationing_layout)
    LinearLayout verificationingLayout;
    @BindView(R.id.import_moneynum_edtext)
    EditText importMoneynumEdtext;
    @BindView(R.id.import_moneynum_gz)
    Button importMoneynumGz;
    @BindView(R.id.import_moneynum_ok)
    Button importMoneynumOk;
    @BindView(R.id.import_moneynum_layout)
    LinearLayout importMoneynumLayout;
    @BindView(R.id.check_money_contentText)
    TextView checkMoneyContentText;
    @BindView(R.id.check_money_btn_gz)
    Button checkMoneyBtnGz;
    @BindView(R.id.check_money_btn_ok)
    Button checkMoneyBtnOk;
    @BindView(R.id.check_money)
    LinearLayout checkMoney;
    @BindView(R.id.transactioning_layout)
    LinearLayout transactioningLayout;
    @BindView(R.id.success_moneynum)
    TextView successMoneynum;
    @BindView(R.id.success_ok_btn)
    Button successOkBtn;
    @BindView(R.id.success_layout)
    LinearLayout successLayout;
    //卡序列号
    private String s_number;
    private String time;
    private int num;
    private String rwNUm;
    private String pass_word = "";
    private String s_user_name;
    private String username;
    private String pz_nums;
    private String cz_num;
    private String cz_time;
    private String run_time;
    private String f39;
    private String type;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_to_help_farmers_withdrawals_btn);
        ButterKnife.bind(this);
        this.setBackBtClick(R.id.base_back_btn);
        this.setTitleText(R.id.base_title_text, "(   " + "助农取款" + "   )");
        ButterKnife.bind(this);
        posFuncs = PosFuncs.getInstace();
        posFuncs.init(this);
        readCardTest();
    }

    private void tradeWithCards(final double money) {
        Logger.e(money + "");
        PinPad.initPinPad(posFuncs);
        new Thread() {
            @Override
            public void run() {

                posFuncs.cardReaderConfig(true, true, true);
                posFuncs.emvTransStart(new PosCallbacks.EmvTransStartCallbacks() {

                    @Override
                    public void onDetectCard(String type) {

                    }

                    @Override
                    public void onConfirmCardInfo(final String pan) {

                        posFuncs.emvConfirmCardInfo(EmvConstants.CONFIRM_OK);

                    }

                    @Override
                    public void onOlinePinEntered(String enc, boolean is_no_pin) {
                        if (!is_no_pin) {

                            try {
                                String pin = PinPad.getPin(bindNum, enc);
                                pass_word = pin;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            Toast.makeText(getApplicationContext(), "请输入密码", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onSuccess(Bundle data) {
                        String channel = data.getString(EmvConstants.CHANNEL);
                        if (EmvConstants.CHANNEL_MAGCARD.equals(channel)) {
//                            appendInfo("MagCard Used\n");
//                            appendInfo("Track1: " + data.getString(EmvConstants.TRACK1) + "\n");
//                            appendInfo("Track2: " + data.getString(EmvConstants.TRACK2) + "\n");
//                            appendInfo("Track3: " + data.getString(EmvConstants.TRACK3) + "\n");
//                            appendInfo("\nFinish\n");
//                            setEmvProcessStatus(false);
                        } else if (EmvConstants.CHANNEL_ICC.equals(channel)) {
//                            appendInfo("ICCard Used\n");
                            track2Data = Utils.formatField57(Utils.getValueFromIccData("57", data.getString(EmvConstants.FEILD_55)));
                            s_number = Utils.getValueFromIccData("5f34", data.getString(EmvConstants.FEILD_55));

                            String ac_type = data.getString(EmvConstants.AC_TYPE);
                            Logger.e("ac_type" + ac_type);
                            Logger.e("Ac Type: " + data.getString(EmvConstants.AC_TYPE) + "\n");
                            Logger.e("Field 55: " + data.getString(EmvConstants.FEILD_55) + "\n");
                            String[] tags =
                                    {
                                            "9F26", "9F27", "9F10", "9F37", "9F36", "95",
                                            "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03", "9F33", "9F34", "9F35",
                                            "9F1E", "84", "9F09", "9F41"
                                    };
                            Field55 = Utils.getField55(tags, data.getString(EmvConstants.FEILD_55));
                            Logger.e("f55" + Field55);
                            if (EmvConstants.AC_TYPE_ARQC.equals(ac_type)) {

                                Bundle bundle = new Bundle();
                                bundle.putString(EmvConstants.RESPONSE_CODE, "3030");
                                posFuncs.emvOnlineResult(new PosCallbacks.EmvOnlineResultCallbacks() {
                                    @Override
                                    public void onSuccess(Bundle data) {
                                        Logger.e("Ac Type: " + data.getString(EmvConstants.AC_TYPE) + "\n");
                                        Logger.e("Field 55: " + data.getString(EmvConstants.FEILD_55) + "\n");

                                    }

                                    @Override
                                    public void onFailed(String error) {

                                    }
                                }, bundle);
                            } else {

                            }
                        } else if (EmvConstants.CHANNEL_ICCL.equals(channel)) {
                            Logger.e("Ac Type: " + data.getString(EmvConstants.AC_TYPE) + "\n");
                            Logger.e("Field 55: " + data.getString(EmvConstants.FEILD_55) + "\n");

                        }
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//
//                                runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        inputMoneyLayout.setVisibility(View.GONE);
//                                        sureRemittanceLayout.setVisibility(View.VISIBLE);
//                                        sureRemittanceMoney.setText("￥" + RemittanceMoney);
//                                        if (make_type.equals("other")) {
//                                            sureRemittanceNum.setText(reInputNumedtext.getText().toString());
//                                            sureRemittanceName.setText(reInputNameedtext.getText().toString());
//                                        } else {
//                                            sureRemittanceNum.setText(bindNum);
//                                            sureRemittanceName.setText(RemittanceName);
//                                        }
//
//
//                                    }
//                                });
//                            }
//                        }).start();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// HH:mm:ss
                                //获取当前时间
                                Date date = new Date(System.currentTimeMillis());

                                time = simpleDateFormat.format(date);

                                run_time = DateUtil.getCurrentTime(DateUtil.M_TIME_PATTERN);
                                cz_time = run_time;
                                num = SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 0);
                                cz_num = String.valueOf(num);
                                SpUtils.getSPUtil(getApplicationContext()).putString("cz_Num", cz_num);
                                SpUtils.getSPUtil(getApplicationContext()).putString("cz_time", cz_time);
                                SpUtils.getSPUtil(getApplicationContext()).putString("cz_money", importMoneynumEdtext.getText().toString());
                                Logger.e("第一次获取" + num);
                                excute(String.valueOf(num), time, bindNum, track2Data, track3Data, importMoneynumEdtext.getText().toString(), pass_word, CardType, Field55);
                                SpUtils.getSPUtil(getApplicationContext()).putInt("s_Num", num + 1);
                                Logger.e("第二次获取" + SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1000));

                            }
                        }).start();
                    }

                    @Override
                    public void onFailed(String error) {

                    }
                }, (int) money, 0);
            }
        }.start();
    }

    /**
     * 读取卡
     */
    private void readCardTest() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                posFuncs.cardReaderConfig(true, true, true);

                posFuncs.emvSimpleFlow(new PosCallbacks.EmvTransStartCallbacks() {
                    @Override
                    public void onDetectCard(String type) {
                        CardType = type;
                        Log.e("", type);
                    }

                    @Override
                    public void onConfirmCardInfo(String pan) {
                        Log.e("", pan);
                        bindNum = pan;
                        Toast.makeText(getApplicationContext(), pan, Toast.LENGTH_SHORT).show();
                        posFuncs.emvConfirmCardInfo(EmvConstants.CONFIRM_OK);

                    }

                    @Override
                    public void onOlinePinEntered(String enc, boolean is_no_pin) {

                    }

                    @Override
                    public void onSuccess(Bundle data) {
                        if (!data.isEmpty()) {


                            Logger.e("", data.getString(EmvConstants.FEILD_55));
                            //如果是磁条卡，就获取二磁信息、上传给银行接口
                            // IC Card    MAG Card    RF Card
                            if (CardType.equals("MAG Card")) {
                                track2Data = data.getString(EmvConstants.TRACK2);
                                track3Data = data.getString(EmvConstants.TRACK3);
                                Logger.e("MAG Card");
                            } else {
                                Logger.e("ic Card");
                                track2Data = Utils.formatField57(Utils.getValueFromIccData("57", data.getString(EmvConstants.FEILD_55)));
                                s_number = Utils.getValueFromIccData("5f34", data.getString(EmvConstants.FEILD_55));
                                String[] tags =
                                        {
                                                "9F26", "9F27", "9F10", "9F37", "9F36", "95",
                                                "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03", "9F33", "9F34", "9F35",
                                                "9F1E", "84", "9F09", "9F41"
                                        };
                                Field55 = Utils.getField55(tags, data.getString(EmvConstants.FEILD_55));
                                Logger.e(s_number + "s_numbers_number");
                            }
Logger.e(track2Data+"track2Data");
//                            String k_bind = SpUtils.getSPUtil(getApplicationContext()).getString("k_bean", "");
//
//                            Gson gson = new Gson();
//                            List<K_binBean> beans = gson.fromJson(k_bind, new TypeToken<List<K_binBean>>() {
//                            }.getType());
//                            Logger.e(beans.size() + "beans.size()");
//                            for (int i = 0; i < beans.size(); i++) {
//                                String lenght = beans.get(i).getK_lenght().substring(1);
//                                String this_kind = bindNum.substring(0, Integer.valueOf(lenght));
//                                if (beans.get(i).getK_bin().equals(this_kind)) {
//                                    type = "bh";
//                                    break;
//                                } else {
//                                    //
//                                    if (i == beans.size() - 1) {
//                                        type = "th";
//                                        Logger.e("他行卡");
//                                        Toast.makeText(ToHelpFarmersWithdrawalsActivity.this, "他行卡", Toast.LENGTH_SHORT).show();
//                                    pleasewycLayout.setVisibility(View.GONE);
//                                    importMoneynumLayout.setVisibility(View.VISIBLE);
////                                        dealingLayout.setVisibility(View.GONE);
////                                        thLayout.setVisibility(View.VISIBLE);
//                                        break;
//                                    } else {
//                                        continue;
//                                    }
//
//                                }
//                            }
//                            if ( type.equals("bh")){
                                pleasewycLayout.setVisibility(View.GONE);
                                verificationingLayout.setVisibility(View.VISIBLE);
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Logger.e("s_number" + s_number);
                                        int Num = SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1);
                                        Logger.e("第一次获取rz" + Num);
                                        excuteVTA(String.valueOf(Num), bindNum, CardType, track2Data, s_number);
                                        SpUtils.getSPUtil(getApplicationContext()).putInt("s_Num", Num + 1);
                                        Logger.e("第二次获取rz" + SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1));
                                    }
                                }).start();
//                            }else {
//
//                            }
                        }

                    }

                    @Override
                    public void onFailed(String error) {
                        Logger.e(error);
                        Toast.makeText(ToHelpFarmersWithdrawalsActivity.this, "请插入卡", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }).start();


    }


    @OnClick({R.id.pleasewyc_image, R.id.pleasewyc_text, R.id.cancal_btn,
            R.id.import_moneynum_gz, R.id.import_moneynum_ok, R.id.check_money_btn_gz,
            R.id.check_money_btn_ok, R.id.success_ok_btn, R.id.sure_printingpeper_okbtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.pleasewyc_image:
                break;
            case R.id.pleasewyc_text:
                break;
            case R.id.cancal_btn:
                //返回主页
                finish();
                break;
            case R.id.import_moneynum_gz:
                //取款金额 更正
                importMoneynumEdtext.setText("");
                break;
            case R.id.import_moneynum_ok:
                //取款金额 确定
                withdrawalMoney = importMoneynumEdtext.getText().toString();
                if (withdrawalMoney.equals("")) {
                    Toast.makeText(this, "请输入取款金额", Toast.LENGTH_SHORT).show();
                } else {

                    if (importMoneynumEdtext.getText().toString().contains(".")) {
                        String mons[] = importMoneynumEdtext.getText().toString().split("\\.");
                        if (mons[1].length() > 2) {
                            Toast.makeText(this, "请输入正确的金额", Toast.LENGTH_SHORT).show();
                        } else {
                            checkMoneyContentText.setText(importMoneynumEdtext.getText().toString());
                            importMoneynumLayout.setVisibility(View.GONE);
                            checkMoney.setVisibility(View.VISIBLE);
                        }

                    } else {
                        checkMoneyContentText.setText("￥" + withdrawalMoney + ".00");
                        importMoneynumLayout.setVisibility(View.GONE);
                        checkMoney.setVisibility(View.VISIBLE);
                    }
                }
                break;
            case R.id.check_money_btn_gz:
                //核对金额 公正
                checkMoney.setVisibility(View.GONE);
                importMoneynumEdtext.setText("");
                importMoneynumLayout.setVisibility(View.VISIBLE);
                break;
            case R.id.check_money_btn_ok:
                //核对金额 确定
                checkMoney.setVisibility(View.GONE);
                transactioningLayout.setVisibility(View.VISIBLE);
                checkMoneyBtnOk.setClickable(false);
                if (importMoneynumEdtext.getText().toString().contains(".")) {
                    DecimalFormat df = new DecimalFormat("######0.00");
                    Double d = Double.parseDouble(importMoneynumEdtext.getText().toString().trim());
                    df.format(d);
//                    enterPin(bindNum, d * 100);
                    tradeWithCards(d * 100);
                } else {
//                    enterPin(bindNum, Integer.parseInt(importMoneynumEdtext.getText().toString().trim()) * 100);
                    tradeWithCards(Integer.parseInt(importMoneynumEdtext.getText().toString().trim()) * 100);
                }
                break;
            case R.id.success_ok_btn:
                //取款成功，确定
                successMoneynum.setText("");
                successLayout.setVisibility(View.GONE);
                surePrintingpeperLayout.setVisibility(View.VISIBLE);

                break;
            case R.id.sure_printingpeper_okbtn:
                surePrintingpeperLayout.setVisibility(View.GONE);
                printingLayout.setVisibility(View.VISIBLE);
                paint();
                break;
        }
    }

    private void paint() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                posFuncs.printerClearBuffer();
                posFuncs.printerAppendLargeTextAlignCenter("烟台银行 通用凭证");
                posFuncs.printerAppendTextline("交易时间 :" + time);
                posFuncs.printerAppendTextline("设备号 :" + Constants.YANTAI_TERMNO);
                posFuncs.printerAppendTextline("操作员 :" + SpUtils.getSPUtil(getApplicationContext()).getString("make_user", ""));

                posFuncs.printerAppendTextline("账号/卡号 :" + bindNum);

                posFuncs.printerAppendTextline("流水号 :" + rwNUm);

                posFuncs.printerAppendTextline("业务类型 :" + "助农取款");
                if (importMoneynumEdtext.getText().toString().contains(".")) {
                    String moneys[] = importMoneynumEdtext.getText().toString().split("\\.");
                    if (moneys[1].length() == 1) {
                        String monses = moneys[0] + "." + moneys[1] + "0";
                        posFuncs.printerAppendTextline("交易金额 :" + monses);
                    } else {
                        posFuncs.printerAppendTextline("交易金额 :" + importMoneynumEdtext.getText().toString());
                    }

                } else {

                    posFuncs.printerAppendTextline("交易金额 :" + importMoneynumEdtext.getText().toString() + ".00");
                }
//                if (type.equals("th")){
//
//                }else {
                    posFuncs.printerAppendTextline("户名 :" + username);
//                }
                posFuncs.printerAppendTextline("凭证序号 :" + pz_nums);
                posFuncs.printerAppendTextline("客户签字确认 :");

                posFuncs.printerAppendTextline("--------------------------------------");
                posFuncs.printerAppendLargeTextAlignCenter("烟台银行 通用凭证");
                posFuncs.printerAppendTextline("交易时间 :" + time);
                posFuncs.printerAppendTextline("设备号 :" + Constants.YANTAI_TERMNO);
                posFuncs.printerAppendTextline("操作员 :" + SpUtils.getSPUtil(getApplicationContext()).getString("make_user", ""));
                String bindx = bindNum.substring(6, bindNum.length() - 5);
                String bindxs = "*";
                for (int i = 0; i < bindx.length(); i++) {
                    bindxs = bindxs + "*";
                }
                posFuncs.printerAppendTextline("账号/卡号 :" + bindNum.substring(0, 6) + bindxs + bindNum.substring(bindNum.length() - 4, bindNum.length()));

                posFuncs.printerAppendTextline("流水号 :" + rwNUm);

                posFuncs.printerAppendTextline("业务类型 :" + "助农取款");
                if (importMoneynumEdtext.getText().toString().contains(".")) {
                    String moneys[] = importMoneynumEdtext.getText().toString().split("\\.");
                    if (moneys[1].length() == 1) {
                        String monses = moneys[0] + "." + moneys[1] + "0";
                        posFuncs.printerAppendTextline("交易金额 :" + monses);
                    } else {
                        posFuncs.printerAppendTextline("交易金额 :" + importMoneynumEdtext.getText().toString());
                    }

                } else {

                    posFuncs.printerAppendTextline("交易金额 :" + importMoneynumEdtext.getText().toString() + ".00");
                }
//                if (type.equals("th")){
//
//                }else {
                    posFuncs.printerAppendTextline("户名 :" + "*" + s_user_name);
//                }

                posFuncs.printerAppendTextline("凭证序号 :" + pz_nums);

                posFuncs.printerAppendTextline("客户签字确认 :");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");


                posFuncs.startPrint(new PosCallbacks.PrintCallbacaks() {
                    @Override
                    public void onSuccess() {
                        Toast.makeText(ToHelpFarmersWithdrawalsActivity.this, "打印成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }

                    @Override
                    public void onFailed(String error) {
                        if (error.equals("Lack Paper")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(ToHelpFarmersWithdrawalsActivity.this, "请确认打印纸安装正确", Toast.LENGTH_SHORT).show();
                                    surePrintingpeperLayout.setVisibility(View.VISIBLE);
                                    printingLayout.setVisibility(View.GONE);
                                }
                            });
                        }
                    }
                });
            }
        }.start();
    }

    /**
     * 调取键盘
     */
    private void enterPin(final String bindNum, final double money) {
        Logger.e(money + "");
        new Thread() {
            @Override
            public void run() {
                posFuncs.enterPin(new PosCallbacks.EnterPinCallbacks() {
                    @Override
                    public void onSuccess(final String enc, boolean is_no_pin) {
                        if (is_no_pin) {
                        } else {
                            Log.e("", enc);
                            new Thread(new Runnable() {
                                @Override
                                public void run() {

//                                    num = SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 0);
//                                    Logger.e("第一次获取" + num);
//                                    excute(String.valueOf(num), bindNum, track2Data, track3Data, importMoneynumEdtext.getText().toString(), enc, CardType, Field55);
//                                    SpUtils.getSPUtil(getApplicationContext()).putInt("s_Num", num + 1);
//                                    Logger.e("第二次获取" + SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1000));

                                }
                            }).start();

                        }
                    }

                    @Override
                    public void onFail(String error) {
                        Toast.makeText(ToHelpFarmersWithdrawalsActivity.this, "交易结束", Toast.LENGTH_SHORT).show();
                        if (!error.equals(null)) {
                            finish();
                        }

                    }

                    @Override
                    public void onInput(int input_num) {
                        Log.e("", String.valueOf(input_num));
                    }
                }, bindNum, (int) money);
            }
        }.start();
    }


    /**
     * 进行请求
     */
    public void excute(String transn, String time, String bindNum, String track2Data, String track3Data, String money, String passWord, String CardTYpe, String Field55) {
        String c_bin_info = SpUtils.getSPUtil(getApplicationContext()).getString("c_bin_info", "null");
        Gson gson = new Gson();
        List<CardBinInfo_bean> beans = gson.fromJson(c_bin_info, new TypeToken<List<CardBinInfo_bean>>() {
        }.getType());
        Logger.e(beans.size() + "beans.size()");
        IsoMessage msg = null;
        CWDInterface inter = new CWDInterface();
        Logger.e(passWord);
        msg = inter.packRequest(type, run_time, beans, transn, bindNum, track2Data, track3Data, money, passWord, CardTYpe, Field55, s_number);
        excuteRequest(msg, "qk");
    }

    /**
     * 账户验证
     */
    public void excuteVTA(String transn, String bindNum, String CardTYpe, String track2Data, String s_number) {
        String c_bin_info = SpUtils.getSPUtil(getApplicationContext()).getString("c_bin_info", "null");
        Gson gson = new Gson();
        List<CardBinInfo_bean> beans = gson.fromJson(c_bin_info, new TypeToken<List<CardBinInfo_bean>>() {
        }.getType());
        Logger.e(beans.size() + "beans.size()");
        IsoMessage msg = null;
        VTAInterface inter = new VTAInterface();
        msg = inter.packRequest(bindNum, beans, transn, track2Data, CardTYpe, String.valueOf(2), s_number);
        excuteRequest(msg, "zhrz");
    }

    /**
     * 冲正
     */
    public void excuteCZ(String transn) {

        IsoMessage msg = null;
        CZInterface inter = new CZInterface();
        msg = inter.packRequest(bindNum, bindNum, Constants.DEMO_F102, cz_num, run_time, cz_time, transn, track2Data, track3Data, CardType, pass_word, String.valueOf(1), Field55, importMoneynumEdtext.getText().toString(), s_number);
        excuteRequest(msg, "zdcz");
    }


    private void excuteRequest(IsoMessage msg, final String op_type) {

        byte[] data = msg.writeData();
        // ��д����ͷ��7�򳤶�ֵ
        int hlen = Constants.ATMP_HEADER_LENGTH;
        int bodylen = data.length - hlen;
        String headF7 = ServiceCommon.appendZero(bodylen, 4);
        System.arraycopy(headF7.getBytes(), 0, data, 28, 4);
        // ����MAC
        if (msg.getField(128) != null) {
//            int start = hlen;
//            int length = data.length - start - 8;
//            byte[] inmac = new byte[length];
//            byte[] outmac = new byte[16];
//            System.arraycopy(data, start, inmac, 0, length);
//            log.debug("MAC����=[{}]", HexT.byteArr2HexStr(inmac));
//            Logger.e(Constants.YANTAI_MACKEY);
//            String mackey = Constants.YANTAI_MACKEY;
//            // MAC99�㷨makֻ��Ҫ16�ֽ���Կ
//            if (mackey.length() > 16) {
//                mackey = mackey.substring(0, 16);
//            }
//            DES3.getMacBlock_99(inmac, mackey.getBytes(), outmac);
//            System.arraycopy(outmac, 0, data, data.length - 8, 8);
//            log.debug("����MAC=[{}]", new String(outmac).substring(0, 8));
            int start = hlen;
            int length = data.length - start - 8 ;
            byte[] inmac = new byte[length];
            byte[] outmac = new byte[16];
            System.arraycopy(data, start, inmac, 0, length);
            System.out.println("MAC数据=["+HexT.byteArr2HexStr(inmac)+"]");
            String mackey = Constants.YANTAI_MACKEY;

            if(Constants.isSM){
                // SM4 MAC919算法
                byte[] mkey = HexT.hexstr2ByteArr(mackey);
                String macval = SMS4.sms4MacBlock_919(inmac, mkey);
                outmac = macval.getBytes();
            }else{
                // MAC99算法mak只需要16字节密钥
                if(mackey.length()>16){
                    mackey = mackey.substring(0, 16);
                }
                DES3.getMacBlock_99(inmac, mackey.getBytes(), outmac);
            }

            System.arraycopy(outmac, 0, data, data.length-8, 8);
            System.out.println("请求MAC=["+new String(outmac).substring(0, 8)+"]");
        }
        byte[] send = null;
        // ���ļ��ܣ���������ʱ��ҵ���ױ��뱨�ļ���
        String encflag = msg.getHeadStringValue(4);
        Logger.e("encflag"+encflag);
        if ("1".equals(encflag)) {
            String tdk = Constants.YANTAI_TDKKEY;
            int lenr = 8 - bodylen % 8;
            byte[] head = new byte[hlen];
            byte[] decdata = new byte[bodylen + lenr];
            System.arraycopy(data, 0, head, 0, hlen);
            System.arraycopy(data, hlen, decdata, 0, bodylen);
            byte[] encdata = DES3.des3Packet(decdata, tdk.getBytes());
            send = new byte[hlen + encdata.length];
            System.arraycopy(head, 0, send, 0, hlen);
            System.arraycopy(encdata, 0, send, hlen, encdata.length);

        }
        else if ("3".equals(encflag)){
            String tdk = Constants.YANTAI_TDKKEY;
            byte[] tdkey = HexT.hexstr2ByteArr(tdk);
            byte[] h7 = new byte[4];
            System.arraycopy(data, 28, h7, 0, 4);
            int orilen = Integer.parseInt(new String(h7));
            int enclen = data.length-Constants.ATMP_HEADER_LENGTH;
            byte[] head = new byte[Constants.ATMP_HEADER_LENGTH];
            byte[] encdata = new byte[enclen];
            System.arraycopy(data, 0, head, 0, Constants.ATMP_HEADER_LENGTH);
            System.arraycopy(data, Constants.ATMP_HEADER_LENGTH, encdata, 0, enclen);
            byte[] decdata = SMS4.unsms4Packet(encdata, tdkey);

            send = new byte[Constants.ATMP_HEADER_LENGTH+orilen];
            System.arraycopy(head, 0, send, 0, Constants.ATMP_HEADER_LENGTH);
            System.arraycopy(decdata, 0, send, Constants.ATMP_HEADER_LENGTH, orilen);
        }

        else {
            send = data;
        }

        CommAdapter adapter = new CommAdapter(Constants.IP, 3551);
        adapter.setHeadlen(4); // ����ͷ��4�ֽ�
        byte[] recv = adapter.doComm(send);

        byte[] recv2 = null;
        byte[] b = new byte[1];
        System.arraycopy(recv, 11, b, 0, 1);
        String rspenc = new String(b);
        log.debug("Ӧ���ļ��ܱ�־:[{}]", rspenc);
        if ("1".equals(rspenc)) {
            String tdk = Constants.YANTAI_TDKKEY;
            byte[] h7 = new byte[4];
            System.arraycopy(recv, 28, h7, 0, 4);
            int orilen = Integer.parseInt(new String(h7));
            int enclen = recv.length - Constants.ATMP_HEADER_LENGTH;
            byte[] head = new byte[Constants.ATMP_HEADER_LENGTH];
            byte[] encdata = new byte[enclen];
            System.arraycopy(recv, 0, head, 0, Constants.ATMP_HEADER_LENGTH);
            System.arraycopy(recv, Constants.ATMP_HEADER_LENGTH, encdata, 0, enclen);
            byte[] decdata = DES3.undes3Packet(encdata, tdk.getBytes());

            recv2 = new byte[Constants.ATMP_HEADER_LENGTH + orilen];
            System.arraycopy(head, 0, recv2, 0, Constants.ATMP_HEADER_LENGTH);
            System.arraycopy(decdata, 0, recv2, Constants.ATMP_HEADER_LENGTH, orilen);
        } else {
            recv2 = recv;
        }

        IsoMessage rsp = null;
        MessageFactory<IsoMessage> fac = new MessageFactory<IsoMessage>();
        try {
            rsp = fac.parseMessage(recv2, 32);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String respcode = rsp.getStringValue(39);
        if ("00".equals(respcode)) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (op_type.equals("zhrz")) {
                        Toast.makeText(getApplicationContext(), "验证成功", Toast.LENGTH_SHORT).show();

                    } else if (op_type.equals("qk")) {
                        if (importMoneynumEdtext.getText().toString().contains(".")) {
                            transactioningLayout.setVisibility(View.GONE);
                            successLayout.setVisibility(View.VISIBLE);
                            successMoneynum.setText(importMoneynumEdtext.getText().toString());
                        } else {
                            transactioningLayout.setVisibility(View.GONE);
                            successLayout.setVisibility(View.VISIBLE);
                            successMoneynum.setText("￥" + withdrawalMoney + ".00");
                        }

                    }

                }
            });
            if (rsp.getField(55) != null) {
                // ARPC��֤
            }
            unpackReSpone(rsp, op_type);
//            inter.unpackReSpone(rsp);
        } else if ("96".equals(respcode)) {
            if (op_type.equals("qk")) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String time = DateUtil.getCurrentTime(DateUtil.M_TIME_PATTERN);
                        run_time = time;
                        num = SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 0);
                        Logger.e("第一次获取" + num);
                        excuteCZ(String.valueOf(num));
                        SpUtils.getSPUtil(getApplicationContext()).putInt("s_Num", num + 1);
                        Logger.e("第二次获取" + SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1000));

                    }
                }).start();


                Gson gson = new Gson();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");// HH:mm:ss
                //获取当前时间
                Date date = new Date(System.currentTimeMillis());
                Logger.e("Date获取当前日期时间" + simpleDateFormat.format(date).replace("/", "") + "UN_DATA");
                StatisticalData_bean bean = new StatisticalData_bean(rwNUm, importMoneynumEdtext.getText().toString(), time, "助农取款", bindNum, username, SpUtils.getSPUtil(getApplicationContext()).getString("make_user", ""), pz_nums);
                String STAT_DATA = SpUtils.getSPUtil(getApplicationContext()).getString(simpleDateFormat.format(date).replace("/", ""), "");

                List<StatisticalData_bean> beans = gson.fromJson(STAT_DATA, new TypeToken<List<StatisticalData_bean>>() {
                }.getType());
                beans.add(bean);
                SpUtils.getSPUtil(getApplicationContext()).putString(simpleDateFormat.format(date).replace("/", "") + "UN_DATA", gson.toJson(beans));
                finish();
            }

        } else {
            f39 = rsp.getStringValue(39);
            log.error("����ʧ��:[{}]-[{}]", respcode, rsp.getStringValue(40));
            Logger.e("����ʧ��:[{}]-[{}]" + respcode + rsp.getStringValue(40));
            Up_RundataUtils up_rundataUtils = new Up_RundataUtils();
            if (op_type.equals("qk")) {
                try {
                    up_rundataUtils.packRequest("0200", "010000",
                            importMoneynumEdtext.getText().toString().trim(), "1", run_time, String.valueOf(num), f39);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } else {
                try {
                    up_rundataUtils.packRequest("0420", "440000",
                            "000000000000000", "3", run_time, String.valueOf(num), f39);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }


            final IsoMessage finalRsp = rsp;
            ToHelpFarmersWithdrawalsActivity.this.runOnUiThread(new Runnable() {
                @SuppressLint("WrongConstant")
                @Override
                public void run() {
//                    Toast.makeText(getApplicationContext(), finalRsp.getStringValue(40), 5000).show();

                    Toast toast = Toast.makeText(getApplicationContext(), finalRsp.getStringValue(40), Toast.LENGTH_LONG);

                    showMyToast(toast, 5 * 1000);
                }
            });

            this.finish();
        }
    }

    public void showMyToast(final Toast toast, final int cnt) {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                toast.show();
            }
        }, 0, 3000);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                toast.cancel();
                timer.cancel();
            }
        }, cnt);
    }


    private void unpackReSpone(IsoMessage response, String op_type) {

        // 如果后台返回，根据需要，可选择显示本次扣取的手续费
        f39 = response.getStringValue(39);
        rwNUm = response.getStringValue(37);
        if (op_type.equals("qk")) {

            Up_RundataUtils up_rundataUtils = new Up_RundataUtils();
            try {
                up_rundataUtils.packRequest("0200", "010000",
                        importMoneynumEdtext.getText().toString().trim(), "0", run_time, String.valueOf(num), f39);
            } catch (IOException e) {
                e.printStackTrace();
            }


            SpUtils.getSPUtil(getApplicationContext()).putString("all_make_type", "qk");

            if (response.getField(28) != null) {
                String f28 = response.getStringValue(28);
                String ccyflag = f28.substring(0, 1);
                String custfee = f28.substring(1);
                custfee = ServiceCommon.multiply(custfee, 100, 4, null);
                if ("C".equals(ccyflag)) {
                    Logger.e("从交易本金扣取手续费：[{}]" + custfee);
                } else if ("D".equals(ccyflag)) {
                    Logger.e("从账户余额扣取手续费：[{}]" + custfee);
                }

            }
            // 如果后台返回，根据需要，可选择显示取款卡余额
            if (response.getField(54) != null) {
                String f54 = response.getStringValue(54);
                int len = f54.length();
                if (len == 40) {
                    String acctype1 = f54.substring(0, 2);
                    String baltype1 = f54.substring(2, 4);
                    String ccy1 = f54.substring(4, 7);
                    String balflag1 = f54.substring(7, 8);
                    String bal1 = f54.substring(8, 20);
                    String balance1 = ServiceCommon.multiply(bal1, 100, 4, null);

                    String acctype2 = f54.substring(20, 22);
                    String baltype2 = f54.substring(22, 24);
                    String ccy2 = f54.substring(24, 27);
                    String balflag2 = f54.substring(27, 28);
                    String bal2 = f54.substring(28, 40);
                    String balance2 = ServiceCommon.multiply(bal2, 100, 4, null);

                    if ("01".equals(baltype1)) {
                        if ("C".equals(balflag1)) {
                            Logger.e("账户余额：[{}]" + balance1);
                        } else if ("D".equals(balflag1)) {
                            balance1 = "-" + balance1;
                            Logger.e("账户余额：[{}]" + balance1);
                        } else {
                            Logger.e("账户余额：[{}]" + balance1);
                        }
                    }
                    if ("02".equals(baltype1)) {
                        if ("C".equals(balflag1)) {
                            Logger.e("可用余额：[{}]" + balance1);
                        } else if ("D".equals(balflag1)) {
                            balance1 = "-" + balance1;
                            Logger.e("可用余额：[{}]" + balance1);
                        } else {
                            Logger.e("可用余额：[{}]" + balance1);
                        }
                    }
                    if ("01".equals(baltype2)) {
                        if ("C".equals(balflag2)) {
                            Logger.e("账户余额：[{}]" + balance2);
                        } else if ("D".equals(balflag2)) {
                            balance2 = "-" + balance2;
                            Logger.e("账户余额：[{}]" + balance2);
                        } else {
                            Logger.e("账户余额：[{}]" + balance2);
                        }
                    }
                    if ("02".equals(baltype2)) {
                        if ("C".equals(balflag2)) {
                            Logger.e("可用余额：[{}]" + balance2);
                        } else if ("D".equals(balflag2)) {
                            balance2 = "-" + balance2;
                            Logger.e("可用余额：[{}]" + balance2);
                        } else {
                            Logger.e("可用余额：[{}]" + balance2);
                        }
                    }


                } else if (len == 20) {
                    String acctype1 = f54.substring(0, 2);
                    String baltype1 = f54.substring(2, 4);
                    String ccy1 = f54.substring(4, 7);
                    String balflag1 = f54.substring(7, 8);
                    String bal1 = f54.substring(8, 20);
                    String balance1 = ServiceCommon.multiply(bal1, 100, 4, null);

                    if ("C".equals(balflag1)) {
                        Logger.e("可用余额：[{}]" + balance1);
                    } else if ("D".equals(balflag1)) {
                        balance1 = "-" + balance1;
                        Logger.e("可用余额：[{}]" + balance1);
                    } else {
                        Logger.e("可用余额：[{}]" + balance1);
                    }

                } else {
                    log.error("返回余额格式不符");
                }
            }

            // 根据需要,显示商户账户余额和客户账户余额
            if (response.getField(123) != null) {
                String f123 = response.getStringValue(123);

                String custcard = ServiceCommon.GBKsubstring(f123, 0, 20);
                custcard = custcard.trim();
                String custname = ServiceCommon.GBKsubstring(f123, 20, 40);
                custname = custname.trim();
                String custccyflag = ServiceCommon.GBKsubstring(f123, 60, 1);
                String custbal = ServiceCommon.GBKsubstring(f123, 61, 12);
                custbal = ServiceCommon.multiply(custbal, 100, 4, null);
                if ("D".equals(custccyflag)) {
                    custbal = "-" + custbal;
                }
                Logger.e("客户剩余可用余额：[{}]" + custbal);

                String mchtcard = ServiceCommon.GBKsubstring(f123, 73, 20);
                mchtcard = mchtcard.trim();
                String mchtname = ServiceCommon.GBKsubstring(f123, 93, 40);
                mchtname = mchtname.trim();
                String mchtccyflag = ServiceCommon.GBKsubstring(f123, 133, 1);
                String mchtbal = ServiceCommon.GBKsubstring(f123, 134, 12);
                mchtbal = ServiceCommon.multiply(mchtbal, 100, 4, null);
                if ("D".equals(mchtccyflag)) {
                    mchtbal = "-" + mchtbal;
                }
                Logger.e("商户剩余可用余额：[{}]" + mchtbal);

            }
            PzGetUtils pzGetUtils = new PzGetUtils();
            pz_nums = pzGetUtils.pzutil(getApplication());


            Gson gson = new Gson();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");// HH:mm:ss
            //获取当前时间
            Date date = new Date(System.currentTimeMillis());
            Logger.e("Date获取当前日期时间" + simpleDateFormat.format(date).replace("/", ""));
            StatisticalData_bean bean = new StatisticalData_bean(rwNUm, importMoneynumEdtext.getText().toString(), time, "现金取款", bindNum, username, SpUtils.getSPUtil(getApplicationContext()).getString("make_user", ""), String.valueOf(pz_nums));
            String STAT_DATA = SpUtils.getSPUtil(getApplicationContext()).getString(simpleDateFormat.format(date).replace("/", ""), "");

            List<StatisticalData_bean> beans = gson.fromJson(STAT_DATA, new TypeToken<List<StatisticalData_bean>>() {
            }.getType());
            beans.add(bean);

            SpUtils.getSPUtil(getApplicationContext()).putString(simpleDateFormat.format(date).replace("/", ""), gson.toJson(beans));


//汇总查询
            String STAT_DATAALL = SpUtils.getSPUtil(getApplicationContext()).getString(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA", "");
            List<Summary_Bean> beanalls = gson.fromJson(STAT_DATAALL, new TypeToken<List<Summary_Bean>>() {
            }.getType());
            if (!beanalls.get(0).getZnqk().equals("")) {
                double money;
                String data[] = beanalls.get(0).getZnqk().split(",");
                Logger.e(data[0] + "aaaaaaaaaaa" + importMoneynumEdtext.getText().toString());
                if (data[0].contains(".") && importMoneynumEdtext.getText().toString().contains(".")) {
                    money = Double.parseDouble(data[0]) + Double.parseDouble(importMoneynumEdtext.getText().toString());
                } else if (data[0].contains(".") && !importMoneynumEdtext.getText().toString().contains(".")) {
                    money = Double.parseDouble(data[0]) + Integer.parseInt(importMoneynumEdtext.getText().toString());
                } else if (!data[0].contains(".") && importMoneynumEdtext.getText().toString().contains(".")) {
                    money = Integer.valueOf(data[0]) + Double.parseDouble(importMoneynumEdtext.getText().toString());
                } else {
                    money = Integer.valueOf(data[0]) + Integer.valueOf(importMoneynumEdtext.getText().toString());
                }
//                BigDecimal n = new BigDecimal("0");

                Logger.e(Double.parseDouble(data[0]) + "bbbbbbbbbbbbbb");
                int num = Integer.valueOf(data[1]) + 1;
                String znqk = money + "," + num;
                Summary_Bean summary_bean = new Summary_Bean(znqk, beanalls.get(0).getXjhk(), beanalls.get(0).getZzhk(), beanalls.get(0).getYdhf(), beanalls.get(0).getLthf(), beanalls.get(0).getSgcc(), beanalls.get(0).getDzh(), beanalls.get(0).getHzd(), beanalls.get(0).getZhgm(), beanalls.get(0).getLwhc(), beanalls.get(0).getKtgs(), "", "", beanalls.get(0).getZhcqy(), beanalls.get(0).getZhcjy(), beanalls.get(0).getHnyqy(), beanalls.get(0).getHnyjy());

                beanalls.clear();
                beanalls.add(summary_bean);
                Logger.e(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA");
                SpUtils.getSPUtil(getApplicationContext()).putString(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA", gson.toJson(beanalls));

            } else {
                int num = 1;
                String money = importMoneynumEdtext.getText().toString();
                String znqk = money + "," + num;
                Summary_Bean summary_bean = new Summary_Bean(znqk, beanalls.get(0).getXjhk(), beanalls.get(0).getZzhk(), beanalls.get(0).getYdhf(), beanalls.get(0).getLthf(), beanalls.get(0).getSgcc(), beanalls.get(0).getDzh(), beanalls.get(0).getHzd(), beanalls.get(0).getZhgm(), beanalls.get(0).getLwhc(), beanalls.get(0).getKtgs(), "", "", beanalls.get(0).getZhcqy(), beanalls.get(0).getZhcjy(), beanalls.get(0).getHnyqy(), beanalls.get(0).getHnyjy());
                beanalls.clear();
                beanalls.add(summary_bean);
                Logger.e(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA");
                SpUtils.getSPUtil(getApplicationContext()).putString(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA", gson.toJson(beanalls));

            }

        } else if (op_type.equals("zdcz")) {
            try {
                Up_RundataUtils up_rundataUtils = new Up_RundataUtils();
                up_rundataUtils.packRequest("0420", "440000",
                        "000000000000000", "2", run_time, String.valueOf(num), f39);
            } catch (IOException e) {
                e.printStackTrace();
            }

            SpUtils.getSPUtil(getApplicationContext()).putString("all_make_type", "zdcz");
            Toast.makeText(this, "网络连接出现问题，已自动冲正", Toast.LENGTH_SHORT).show();
            this.finish();
        } else {
            SpUtils.getSPUtil(getApplicationContext()).putString("all_make_type", "zhrz");
            String f123[] = response.getStringValue(123).split("\\|");
            username = f123[2];
            s_user_name = username.substring(1, username.length());


            final String f39 = response.getStringValue(39);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    handler = new Handler();
                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            verificationingLayout.setVisibility(View.GONE);
                            importMoneynumLayout.setVisibility(View.VISIBLE);
                        }
                    };
                    handler.postDelayed(runnable, 1000);

                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacks(runnable);
        }
    }

    @Override
    public void finish() {
        super.finish();
    }


}
